package uk.co.kevinlockwood.kol.droid.activities;

import uk.co.kevinlockwood.kol.droid.DroidHelpers;
import uk.co.kevinlockwood.kol.droid.G;
import uk.co.kevinlockwood.kol.droid.R;
import uk.co.kevinlockwood.kol.droid.services.KoLMessageService;
import uk.co.kevinlockwood.kol.messages.KoLMessage;
import uk.co.kevinlockwood.kol.messages.KoLMessageAdapter;
import uk.co.kevinlockwood.kol.messages.KoLMessageServiceBinder;
import uk.co.kevinlockwood.kol.pages.ApiStatusPage;
import uk.co.kevinlockwood.kol.pages.KoLPageBuilder;
import uk.co.kevinlockwood.kol.pages.SubmitNewChat;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ListView;

public class Chat extends Activity implements OnClickListener, OnKeyListener, ServiceConnection, Handler.Callback {
	private KoLMessageServiceBinder binder;
	private KoLMessageAdapter chatdisplay;
	private KoLPageBuilder builder;
	private Handler messageHandler;
	private SharedPreferences settings;
	private Integer playerid;
	private String pwdhash;
	private String sessionid;
	private EditText textinput;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		DroidHelpers.trace("Chat.onCreate()");
		super.onCreate(savedInstanceState);
		try {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			settings = getSharedPreferences(G.PREFS_NAME, MODE_PRIVATE);
			sessionid = settings.getString(G.SESSION_ID, "");
			builder = new KoLPageBuilder(this, sessionid);
			setContentView(R.layout.chat);
		} catch (Exception e) {
			DroidHelpers.printStackTrace(e);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		DroidHelpers.trace("Chat.onStart()");
		DroidHelpers.setupActivity(this, settings);
		textinput = (EditText)findViewById(R.id.textinput);
		textinput.setOnKeyListener(this);
		ApiStatusPage p = builder.buildPage(new ApiStatusPage());
		playerid = p.getPlayerId();
		pwdhash = p.getPwdHash();
		DroidHelpers.debug("got playerid=[",playerid,"] pwdhash=[",pwdhash,"]");
		findViewById(R.id.sendbutton).setOnClickListener(this);

		Intent i = new Intent(this, KoLMessageService.class);
		startService(i);
		int textSize = settings.getInt(G.FONT_SIZE, 18);
		chatdisplay = new KoLMessageAdapter(this, R.layout.message, textSize);
		((ListView)findViewById(R.id.messagelist)).setAdapter(chatdisplay);
		messageHandler = new Handler(this);
		bindService(i, this, BIND_AUTO_CREATE);
		DroidHelpers.debug("KoLMessageService started by Chat");
	}

	@Override
	protected void onDestroy() {
		DroidHelpers.trace("Chat.onDestroy()");
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		DroidHelpers.trace("Chat.onStop()");
		unbindService(this);
		super.onStop();
	}

	private void submitChat() {
		String msg = textinput.getText().toString();
		textinput.setText("");
		if (msg != null && !"".equals(msg)) {
			DroidHelpers.log("sending message [",msg,"]");
			SubmitNewChat s = builder.buildPage(new SubmitNewChat(playerid, pwdhash, msg));
			binder.addMessage(s.getReturnMessage());
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sendbutton:
			submitChat();
			break;
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
			submitChat();
			return true;
		}
		return false;
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (msg.obj instanceof KoLMessage) {
			chatdisplay.add((KoLMessage)msg.obj);
			return true;
		} else if (msg.obj instanceof KoLMessageServiceBinder) {
			binder = (KoLMessageServiceBinder)msg.obj;
			return true;
		} else {
			DroidHelpers.log("Chat received unrecognised message [",msg.obj,"]");
			return false;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.chat_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String msg = null;
		switch(item.getItemId()) {
		case R.id.msg_channel:
			msg = "/channel ";
			break;
		case R.id.msg_clannies:
			msg = "/clannies";
			break;
		case R.id.msg_emote:
			msg = "/me ";
			break;
		case R.id.msg_friend:
			msg = "/friend ";
			break;
		case R.id.msg_ignore:
			msg = "/ignore ";
			break;
		case R.id.msg_listen:
			msg = "/listen ";
			break;
		case R.id.msg_trivial:
			msg = "/trivial";
			break;
		case R.id.msg_updates:
			msg = "/updates";
			break;
		case R.id.msg_who:
			msg = "/who ";
			break;
		case R.id.msg_whois:
			msg = "/whois ";
			break;
		case R.id.options:
			Intent i = new Intent(this, Options.class);
			startActivity(i);
			break;
		default:
			DroidHelpers.log("unrecognised id ",item.getItemId());
			return super.onOptionsItemSelected(item);
		}
		textinput.setText(msg);
		return true;
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		DroidHelpers.trace("Chat.onServiceConnected(",name,", ",service,")");
		binder = (KoLMessageServiceBinder)service;
		if (null != binder) binder.haveHandler(messageHandler);
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		DroidHelpers.trace("Chat.onServiceConnected(",name,")");
	}
}
